package com.mywork.test.validatetest;


import lombok.Data;

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @ProjectName: testdemo
 * @ClassName: com.mywork.test.validatetest
 * @Author: lsx
 * @Date: 2023/06/28 17:01
 **/
public class ValidationDemo {

    public static void main(String[] args) {
        // 创建 ValidatorFactory
        ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

        // 创建 Validator
        Validator validator = validatorFactory.getValidator();

        // 创建需要验证的对象
        User user = new User();
        user.setName(null);
        user.setAge(16);

        List<Student> list = new ArrayList<>();
        list.add(new Student());

        user.setStudentList(list);

        // 执行验证
        Set<javax.validation.ConstraintViolation<User>> violations = validator.validate(user);
        for (javax.validation.ConstraintViolation<User> violation : violations) {
            System.out.println(violation.getMessage());
        }
    }


    @Data
    public static class User {
        @NotNull(message = "姓名不能为空")
        @Size(min = 1, max = 10, message = "姓名长度必须在1到10之间")
        private String name;

        @NotNull(message = "年龄不能为空")
        private Integer age;

        @NotEmpty(message = "学生集合不能为空！")
        private List<Student> studentList;


    }


    @Data
    public static class Student {
        @NotNull(message = "姓名不能为空")
        @Size(min = 1, max = 10, message = "姓名长度必须在1到10之间")
        private String name;

        @NotNull(message = "年龄不能为空")
        private Integer age;


        // Getters and setters...

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }
    }
}
